Note the difference between delete and delete[] in C++

  • 2020-04-01 21:33:08
  • OfStack

      C++ tells us to use delete when retrieving the memory space of a single object allocated with new and delete[] when retrieving the memory space of a group of objects allocated with new[].   With respect to new[] and delete[], there are two cases :(1) allocate and reclaim space for basic data types; (2) allocate and reclaim space for custom types.

See the following program.


#include <iostream>;
using namespace std;

class T {
public:
  T() { cout << "constructor" << endl; }
  ~T() { cout << "destructor" << endl; }
};

int main()
{
  const int NUM = 3;

  T* p1 = new T[NUM];
  cout << hex << p1 << endl;
  //  delete[] p1;
  delete p1;

  T* p2 = new T[NUM];
  cout << p2 << endl;
  delete[] p2;
} 

You can run this program yourself, and look at the different results of delete p1 and delete[] p1, and I won't post the results here.

      From the result of operation, we can see that in the process of space recovery of delete p1, only the object p1[0] calls the destructor, while other objects such as p1[1] and p1[2] do not call their own destructor, which is the crux of the problem. With delete[], all objects call their destructors first before the space is reclaimed.           Objects of primitive types do not have destructors, so it should be possible to reclaim the array space composed of primitive types with delete and delete[]. But for an array of class objects, you can only use delete[]. For a single object of new, space can only be reclaimed with delete and not with delete[].           So a simple usage principle is: new and delete, new[] and delete[] are used accordingly.

 

  I understand, when using the delete to release new int [] application memory space, because its as the basic data types without the destructor, so using the delete and delete [] is the same, both release application memory space, if a custom data types, a destructor, use new [] application space, must use the delete [] to release, because must delete [] when one by one, calling the destructor for an array of objects, and then release the space, if use the delete, only call the first object's destructor, If the destructor of the following object is not called, is its space free?


Related articles: